package com.jiejie.service.impl;

import com.jiejie.entity.Movie;
import com.jiejie.mapper.MovieMapper;
import com.jiejie.service.RecommendService;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RecommendServiceImpl implements RecommendService {
    @Resource
    private MovieMapper movieMapper;
    @Resource
    private DataModel dataModel;

    @Override
    public List<Movie> getRecommentProductByUser(Integer userId, Integer howMany) {
        return null;
    }

    @Override
    public List<Movie> getRecommentMovieByMovie(Integer customerId, Integer movieId, Integer howMany) {
        List<Movie> movieList = null;
        try {
            /*计算相似度，相似度的计算方式很多，采用基于皮尔逊相关性的相似度*/
            ItemSimilarity itemSimilarity = new PearsonCorrelationSimilarity(dataModel);
            /*构建推荐器，基于物品的协同过滤推荐*/
            GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dataModel,itemSimilarity);
            long startTime = System.currentTimeMillis();
            /*推荐商品*/
            List<RecommendedItem> recommendedItemList = recommender.recommendedBecause(customerId,movieId,howMany);

            List<Integer> movieIds = new ArrayList<>();

            for (RecommendedItem recommendedItem: recommendedItemList) {
                System.out.println("recommendedItem:" + recommendedItem);
                movieIds.add((int) recommendedItem.getItemID());
            }
                System.out.println("推荐出来的电影的Id集合：" + movieIds);

                /*根据电影Id查询商品*/
                if (movieIds != null && movieIds.size()>0){
                    movieList = movieMapper.selectBatchIds(movieIds);
                }else {
                    movieList = new ArrayList<>();
                }
                System.out.println("电影的数量是" + movieList.size() + ",耗时:"+(System.currentTimeMillis()-startTime));
        } catch (TasteException e) {
            throw new RuntimeException(e);
        }


        return movieList;
    }
}
